package sdk

import (
	"fmt"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111" // 引入sms
	"likeadmin/util"
)

var SMSTencent = smsTencent{}

type smsTencent struct{}

func (s smsTencent) Send(templateId string, phone string, param string) (err error) {

	engineConf := util.SettingUtil.GetSmsEngineConf("qcloud")

	// 将json 转换成 []string
	var ParamMap map[string]interface{}
	var Param []string

	if param != "" {
		ParamMap, err = util.ToolsUtil.JsonToMap(param)
		if err != nil {
			return err
		}
	}

	for _, value := range ParamMap {
		switch v := value.(type) {
		case int:
			Param = append(Param, fmt.Sprintf("%d", v))
		case string:
			Param = append(Param, v)
		default:
			Param = append(Param, fmt.Sprintf("%v", v))
		}
	}

	credential := common.NewCredential(
		engineConf.SecretId,
		engineConf.SecretKey,
	)

	cpf := profile.NewClientProfile()
	cpf.HttpProfile.ReqMethod = "POST"
	cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"
	cpf.SignMethod = "HmacSHA1"

	client, _ := sms.NewClient(credential, "ap-guangzhou", cpf)
	request := sms.NewSendSmsRequest()
	request.SmsSdkAppId = common.StringPtr(engineConf.AppId)
	request.SignName = common.StringPtr(engineConf.Sign)
	request.TemplateId = common.StringPtr(templateId)
	request.TemplateParamSet = common.StringPtrs(Param)

	/* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
	 * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
	request.PhoneNumberSet = common.StringPtrs([]string{"+86" + phone})
	request.SessionContext = common.StringPtr("")
	request.ExtendCode = common.StringPtr("")
	request.SenderId = common.StringPtr("")

	// 通过client对象调用想要访问的接口，需要传入请求对象
	//response, err := client.SendSms(request)
	_, err = client.SendSms(request)
	// 处理异常
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return
	}
	// 非SDK异常，直接失败。实际代码中可以加入其他的处理。
	if err != nil {
		return
	}
	//b, _ := json.Marshal(response.Response)
	// 打印返回的json字符串
	//fmt.Printf("%s", b)
	return
}
